package cn.wei.youvie.controller;

import cn.wei.youvie.common.annotation.AuthCheck;
import cn.wei.youvie.common.constant.UserConstant;
import cn.wei.youvie.common.exception.BusinessException;
import cn.wei.youvie.common.exception.ThrowUtils;
import cn.wei.youvie.common.servlet.BaseResponse;
import cn.wei.youvie.common.servlet.DeleteRequest;
import cn.wei.youvie.common.servlet.ErrorCode;
import cn.wei.youvie.common.servlet.ResultUtils;
import cn.wei.youvie.domain.dto.section.SectionAddRequest;
import cn.wei.youvie.domain.dto.section.SectionEditRequest;
import cn.wei.youvie.domain.dto.section.SectionQueryRequest;
import cn.wei.youvie.domain.dto.section.SectionUpdateRequest;
import cn.wei.youvie.domain.entity.Section;
import cn.wei.youvie.domain.entity.User;
import cn.wei.youvie.domain.vo.SectionVO;
import cn.wei.youvie.service.SectionService;
import cn.wei.youvie.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/section")
@Slf4j
public class SectionController {


    @Resource
    private SectionService sectionService;

    @Resource
    private UserService userService;

    /**
     * 新建章节
     */
    @PostMapping("/add")
    public BaseResponse<Integer> addSection(@RequestBody SectionAddRequest sectionAddRequest, HttpServletRequest request) {
        Integer chapterId = sectionService.add(sectionAddRequest, request);
        return ResultUtils.success(chapterId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSection(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        boolean removed = sectionService.deleteSection(deleteRequest, request);
        return ResultUtils.success(removed);
    }

    /**
     * 更新（仅管理员）
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateSection(@RequestBody SectionUpdateRequest sectionUpdateRequest, HttpServletRequest request) {
        boolean updated = sectionService.updateSection(sectionUpdateRequest, request);
        return ResultUtils.success(updated);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get/vo")
    public BaseResponse<SectionVO> getSectionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Section section = sectionService.getById(id);
        if (section == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(sectionService.getSectionVO(section, request));
    }

    /**
     * 分页获取列表（仅管理员）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Section>> listSectionByPage(@RequestBody SectionQueryRequest sectionQueryRequest) {
        long current = sectionQueryRequest.getCurrent();
        long size = sectionQueryRequest.getPageSize();
        Page<Section> sectionPage = sectionService.page(new Page<>(current, size),
                sectionService.getQueryWrapper(sectionQueryRequest));
        return ResultUtils.success(sectionPage);
    }

    /**
     * 分页获取列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SectionVO>> listSectionVOByPage(@RequestBody SectionQueryRequest sectionQueryRequest,
                                                             HttpServletRequest request) {
        return null;
    }

    /**
     * 分页获取当前用户创建的资源列表
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<SectionVO>> listMySectionVOByPage(@RequestBody SectionQueryRequest sectionQueryRequest,
                                                               HttpServletRequest request) {
        if (sectionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = sectionQueryRequest.getCurrent();
        long size = sectionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Section> chapterPage = sectionService.page(new Page<>(current, size),
                sectionService.getQueryWrapper(sectionQueryRequest));
        return ResultUtils.success(sectionService.getSectionVOPage(chapterPage, request));
    }

    /**
     * 分页搜索（从 ES 查询，封装类）
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<SectionVO>> searchSectionVOByPage(@RequestBody SectionQueryRequest sectionQueryRequest,
                                                               HttpServletRequest request) {
        return null;
    }

    /**
     * 编辑（用户）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editSection(@RequestBody SectionEditRequest sectionEditRequest, HttpServletRequest request) {
        if (sectionEditRequest == null || sectionEditRequest.getSectionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Section section = new Section();
        BeanUtils.copyProperties(sectionEditRequest, section);

        User loginUser = userService.getLoginUser(request);
        long id = sectionEditRequest.getSectionId();
        // 判断是否存在
        Section oldSection = sectionService.getById(id);
        ThrowUtils.throwIf(oldSection == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = sectionService.updateById(section);
        return ResultUtils.success(result);
    }

}
